package com.wip.reportingclient.services.util;

import java.util.Collections;
import java.util.List;

import org.springframework.stereotype.Component;

@Component
public class CalculatorUtil {

	public int calculatePercentile(final int percentile, List<Integer> values) {

		// sort the list
		Collections.sort(values);

		final int numberOfElements = values.size();
		final double rawResult = percentile * (numberOfElements + 1) / 100.0;

		// return values.get(method1(rawResult));
		// return values.get(method1(rawResult));
		return method1(rawResult, values);

	}

	/*
	 * {3.6, 4, 4.5, 4.5, 5.7, 5.9, 6, 6.5, 7.1, 7.8, 8, 8.1, 9, 9.2, 9.4}
	 */
	/*
	 * The simplest option is to round down to the nearest integer (whole
	 * number), which in this case is 14. So, the 90th percentile corresponds to
	 * the value of the 14th data point. Reading across the ordered list that
	 * gives us the value 9.2.
	 */
	private int method1(double rawResult, List<Integer> values) {
		//
		return values.get((int) Math.floor(rawResult)-1);
	}

	/*
	 * An alternative approach is not to round that value of 14.4, but to take
	 * the values on either side of it (the values in position 14 and 15) and
	 * derive some intermediate value from those. The simplest way of doing this
	 * is take the simple average of the two values, so in our example the 90th
	 * percentile would be 9.3 (the mean of 9.2 and 9.4).
	 */
	private double method2(double rawResult, List<Integer> values) {
		return (values.get((int) Math.floor(rawResult)) + values.get((int) Math
				.ceil(rawResult))) / 2.0;

	}

	public double calculateAverage(List<Integer> values) {

		double total = 0.0;
		for (int i = 0; i < values.size(); i++)// runs the loop to calculate all
												// numbers
		{
			total += values.get(i);
		}
		return total / values.size();

	}

	public double calculateStandardDeviation(List<Integer> values) {
		double mean = calculateAverage(values);

		double sd2 = 0.0;
		for (int i = 0; i < values.size(); i++)// runs the loop to calculate all
												// numbers
		{
			sd2 += (Math.pow((values.get(i) - mean), 2));
		}
		return sd2 / (values.size() - 1);
	}
}
